package club.yunqiang.arithmetic.sort;

import java.util.Arrays;

/**
 * 冒泡排序
 * 
 * @author YunQiang
 *
 */
public class BubbleSort {

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static void sort(Comparable[] comparables) {
		for (int i = 0; i < comparables.length; i++) {
			boolean flag = false;
			for (int j = 0; j < comparables.length - i - 1; j++) {
				if (comparables[j + 1].compareTo(comparables[j]) < 0) {
					flag = true;
					swap(comparables, j, j + 1);
				}
			}
			if (flag == false) {
				break;
			}
		}
	}

	/**
	 * 交换数组中的两个对象
	 *
	 * @param array数组
	 * @param i数组下标
	 * @param j数组下标
	 */
	private static void swap(Object[] array, int i, int j) {
		Object temp = array[i];
		array[i] = array[j];
		array[j] = temp;
	}

	public static void main(String[] args) {
		Integer[] integers = SortTestHelper.generateRandomArray(1000, 0, 1000);
		Integer[] copyOf = Arrays.copyOf(integers, integers.length);
		System.out.println(Arrays.toString(integers));

		SortTestHelper.testSort(BubbleSort.class.getName(), integers);
		System.out.println(Arrays.toString(integers));
		
		SortTestHelper.testSort(InsertionSort.class.getName(), copyOf);
		System.out.println(Arrays.toString(copyOf));
		
		System.exit(0);
	}

}
